package com.glory.brepda.activity.mfg;

import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.AddCarrierDataAdapter;
import com.glory.brepda.adapter.MaterielAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.Constant;
import com.glory.brepda.entity.EqpBody;
import com.glory.brepda.entity.EqpEntity;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

public class WBWorkBeginActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.tvLotState)
    TextView tvLotState;
    @BindView(R.id.tvpartName)
    TextView tvpartName;
    @BindView(R.id.tvPackageType)
    TextView tvPackageType;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.etEqpWorkID)
    FreeUI_ClearEditText etEqpWorkID;
    @BindView(R.id.tvBDNum)
    TextView tvBDNum;
    @BindView(R.id.tvStepDesc)
    TextView tvStepDesc;
    @BindView(R.id.tvRecipeID)
    TextView tvRecipeID;
    @BindView(R.id.etComment)
    FreeUI_ClearEditText etComment;
    @BindView(R.id.etMaterielModel)
    FreeUI_ClearEditText etMaterielModel;
    @BindView(R.id.rvMaterielModelList)
    RecyclerView rvMaterielModelList;
    @BindView(R.id.etMaterielBox)
    FreeUI_ClearEditText etMaterielBox;
    @BindView(R.id.rvMaterielBoxList)
    RecyclerView rvMaterielBoxList;
    @BindView(R.id.rvMaterielList)
    RecyclerView rvMaterielList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvPauseStatus)
    TextView tvPauseStatus;
    @BindView(R.id.etPSM)
    FreeUI_ClearEditText etPSM;
    @BindView(R.id.lotScan)
    ImageView lotScan;
    @BindView(R.id.eqpScan)
    ImageView eqpScan;
    @BindView(R.id.psmScan)
    ImageView psmScan;
    private static final int REQUEST_CODE_TEXT1 = 1001;
    private static final int REQUEST_CODE_TEXT2 = 1002;
    private static final int REQUEST_CODE_TEXT3 = 1003;
    private AddCarrierDataAdapter materielModelAdapter;
    private AddCarrierDataAdapter materielBoxAdapter;
    private MaterielAdapter materielAdapter;
    private List<String> mDurablelist;
    private String mDurable;
    private String woid;
    private LotInfoEntity lotInfo;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_track_in_wb;
    }

    @Override
    protected void initView() {
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        setMainLayout(llMain);
        etLot.requestFocus();
        initRecyclerView(rvMaterielModelList, this);
        initRecyclerView(rvMaterielBoxList, this);
        initRecyclerView(rvMaterielList, this);
        materielModelAdapter = getCarrierAdapter();
        rvMaterielModelList.setAdapter(materielModelAdapter);
        materielBoxAdapter = getCarrierAdapter();
        rvMaterielBoxList.setAdapter(materielBoxAdapter);

        materielAdapter = new MaterielAdapter(null);
        materielAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        materielAdapter.isFirstOnly(true);
        rvMaterielList.setAdapter(materielAdapter);

//        etMaterielModel.setVisibility(Constant.CARRIER_DURABLELIST ? View.VISIBLE : View.GONE);
//        etMaterielBox.setVisibility(Constant.CARRIER_DURABLELIST ? View.VISIBLE : View.GONE);
        initEdit(etMaterielModel, s -> {

            if (etLot.equals("")) {
                showToast("请先扫描批次号!", false);
                return;
            }


            if (materielModelAdapter.getData().contains(s)) {
                showToast("当前载具已添加到载具列表中", false);
                return;
            }

            if (mDurable.equals(s)) {
                materielModelAdapter.getData().add(s);
                materielModelAdapter.notifyDataSetChanged();
            } else {
                showToast("当前载具不匹配!", false);
            }

        });

        initEdit(etMaterielBox, s -> {

            if (etLot.equals("")) {
                showToast("请先扫描批次号!", false);
                return;
            }

            if (materielBoxAdapter.getData().contains(s)) {
                showToast("当前料盒已添加到列表中", false);
                return;
            }

            if (mDurable.equals(s)) {
//            if (mDurablelist.contains(s)) {
                materielBoxAdapter.getData().add(s);
                materielBoxAdapter.notifyDataSetChanged();
                etMaterielBox.setText("");
                etMaterielBox.requestFocus();
            } else {
                showToast("当前料盒号不匹配!", false);
            }
        });

        initEdit(etLot, s -> {
            //获取lot信息
            LotUtils.searchLotInfo(WBWorkBeginActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
                @Override
                public void onSuccess(LotInfoEntity lot) {
                    lotInfo = lot;
                    tvPauseStatus.setText(lot.getLOT().getHOLDSTATE());
                    Constant.LIMITPACKAGETYPEQTY = lot.getLIMITPACKAGETYPEQTY();
                    Constant.PACKAGETYPE = lot.getPACKAGETYPE();
                    Constant.WIRESPEC = lot.getWIRESPEC();
                    Constant.BDCODE = lot.getBD_CODE();
                    LotInfoEntity.LotBean response = lot.getLOT();
                    Constant.PARTNAME = response.getPARTNAME();
                    woid = response.getWOID();
                    mDurable = response.getDURABLEID();
                    tvBDNum.setText(lot.getBD_CODE());
                    mDurablelist = lot.getDURABLELIST();
                    tvLotState.setText(response.getSTATE());
                    tvpartName.setText(response.getPARTNAME());
                    tvStepDesc.setText(response.getSTEPDESC());
                    tvPackageType.setText(lot.getPACKAGETYPE());
                    materielModelAdapter.setNewData(mDurablelist);
                    etEqpWorkID.requestFocus();
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t, "LOTQUERY");
                }
            });
        });

        initEdit(etEqpWorkID, s -> getWqpInfo(s));
    }

    private void getWqpInfo(String eqpID) {
        FreeUI_EntityCallBack<BaseResponseBean<EqpEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EqpEntity>>
                (new TypeToken<BaseResponseBean<EqpEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EqpEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(WBWorkBeginActivity.this, true, getSupportFragmentManager())) {
                    EqpEntity body = response.body().getResponse().getBody();
                    materielAdapter.setNewData(body.equipmentlist);
                    etMaterielModel.requestFocus();
                }

            }

            @Override
            public void onError(Response<BaseResponseBean<EqpEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "MLOTKITTING");

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "EQPBYID");
        EqpBody eqpBody = new EqpBody("",eqpID,"");
        map.add("EQUIPMENT",new JsonParser().parse(new Gson().toJson(eqpBody)).getAsJsonObject());
        NetUtils.requestPostNet("IF.BREQUERYEQP", "Common", WBWorkBeginActivity.this, map, callBack);
    }

    @Override
    protected void initData() {

        lotScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT1);
            }
        });
        eqpScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT2);
            }
        });
        psmScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT3);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && data != null) {
            String qrResult = data.getStringExtra("SCAN_RESULT"); // 获取扫码结果
            if (qrResult != null) {
                switch (requestCode) {
                    case REQUEST_CODE_TEXT1:
                        etLot.setText(qrResult);
                        break;
                    case REQUEST_CODE_TEXT2:
                        etEqpWorkID.setText(qrResult);
                        break;
                    case REQUEST_CODE_TEXT3:
                        etPSM.setText(qrResult);
                        break;
                }
            }

        }
    }



    @OnClick(R.id.tvBaseSubmit)
    public void onViewClicked() {
//        if (actionControl("Submit23")) {
//            return;
//        }

        if (tvLotState.getText().toString().equals("待投产")) {
            showConfirmDialog("批次未投产，请联系计划部执行投产");
            return;
        }

//        if (tvLotState.getText().toString().equals("正在作业")) {
//            showConfirmDialog("批次正在作业，请直接操作出站功能");
//            return;
//        }
//        WBLOTTRACKIN
        LotUtils.lotTrackIn(getSupportFragmentManager(),lotInfo,materielBoxAdapter.getData(),woid,"MULTIDEVICELOTTRACKIN", this, getText(etEqpWorkID), getText(etLot), materielModelAdapter.getData(), "DefaultTrackIn");
    }
}
